Write an efficient function that checks whether any permutation of an input string is a palindrome.
You can assume the input string only contains lowercase letters.
Examples:
"But 'ivicc' isn't a palindrome!"
If you had this thought, read the question again carefully. We're asking if any permutation of the string is a palindrome. Spend some extra time ensuring you fully understand the question before starting. Jumping in with a flawed understanding of the problem doesn't look good in an interview.
Our approach is to check that each character appears an even number of times, allowing for only one character to appear an odd number of times (a middle character). This is enough to determine if a permutation of the input string is a palindrome.
We iterate through each character in the input string, keeping track of the characters we’ve seen an odd number of times using a set unpaired_characters.
As we iterate through the characters in the input string:
Finally, we just need to check if less than two characters don’t have a pair.
def has_palindrome_permutation(the_string):
# Track characters we've seen an odd number of times
unpaired_characters = set()
for char in the_string:
if char in unpaired_characters:
unpaired_characters.remove(char)
else:
unpaired_characters.add(char)
# The string has a palindrome permutation if it
# has one or zero characters without a pair
return len(unpaired_characters) <= 1
time, since we're making one iteration through the characters in the string.
Our unpaired_characters set is the only thing taking up non-constant space. We could say our space cost is as well, since the set of unique characters is less than or equal to . But we can also look at it this way: there are only so many different characters. How many? The ASCII character set has just 128 different characters (standard english letters and punctuation), while Unicode has 110,000 (supporting several languages and some icons/symbols). We might want to treat our number of possible characters in our character set as another variable and say our space complexity is . Or we might want to just treat it as a constant, and say our space complexity is .
One of the tricks was to use a dictionary or set.
This is the most common way to get from a brute force approach to something more efficient. Especially for easier problems.
I even know interviewers who just want to hear you say "dictionary", and once they hear that they'll say, "Great, let's move on."
So always ask yourself, right from the start: "Can I save time by using a dictionary?"
Want more examples of dictionaries unlocking the optimal answer for a coding interview question? Check out these other questions.
Do you have an answer?
Wanna review this one again later? Or do you feel like you got it all?
Mark as done Pin for review laterReset editor
Powered by qualified.io